import json
import subprocess
from datetime import datetime

from devpi import login
from devpi.main import get_pluginmanager, parse_args, Hub
from devpi.upload import main_fromfiles
from devpi_common.url import URL

devpi_index = "root/custom"


def devpi_login():
    pm = get_pluginmanager()
    args = parse_args(['', 'login', "root", "--password="], pm=pm)
    args.index = devpi_index
    hub = Hub(args, file=None, pm=pm)
    login.main(hub, args)


def devpi_upload(file_paths):
    pm = get_pluginmanager()
    args = parse_args(['', 'upload'], pm=pm)
    args.index = devpi_index
    args.path = file_paths
    hub = Hub(args, file=None, pm=pm)
    main_fromfiles(hub, args)


is_check = False


def check_for_update(package_name):
    global is_check
    if is_check:
        return
    is_check = True
    from pkg_resources import get_distribution
    # 获取当前安装的版本
    current_version = get_distribution(package_name).version
    last_version = get_last_version(package_name)
    if current_version != last_version:
        print(f"{package_name}: 当前版本是{current_version} 最新版本:{last_version}, 请更新pika-qt")
    else:
        print(f"{package_name}: {current_version} 已经是最新的版本!!!")


def get_json_data(hub):
    hub.set_quiet()
    current = hub.current
    args = hub.args

    path_url = URL(args.path)

    current = hub.current
    url = None
    if path_url.scheme in ('http', 'https'):
        url = path_url
    elif not path_url.path.startswith("/") and not current.index:
        hub.fatal("cannot use relative path without an active index")
    elif current.index:
        url = current.index_url.addpath(path_url.path)
    elif current.root_url:
        url = current.root_url.addpath(path_url.path)
    else:
        hub.fatal("no server currently selected")
    if path_url.query:
        url = url.replace(query=path_url.query)
    r = hub.http_api("get", url, quiet=True, check_version=False)
    if hub.args.verbose:
        hub.line("GET REQUEST sent to %s" % url)
        for name in sorted(r.headers):
            hub.line("%s: %s" % (name.upper(), r.headers[name]))
        hub.line()
    return r.result


def get_update_when(hub):
    json_dict = get_json_data(hub)
    version_when = {}
    for version in json_dict:
        json_dict[version]["description"] = {}
        json_dict[version]["requires_dist"] = {}
        item = json_dict[version]
        links = item["+links"]
        when = None
        for link in links:
            herf = link["href"]
            log = link["log"]
            when = log[0]["when"]
            if herf[-3:] == "whl":
                version_when[version] = when
        if version not in version_when:
            version_when[version] = when
    return version_when


def get_last_version(package_name):
    pm = get_pluginmanager()
    args = parse_args(['', 'getjson', package_name], pm=pm)
    args.index = devpi_index
    hub = Hub(args, file=None, pm=pm)
    update_when = get_update_when(hub)
    verison_sort = sorted(update_when, key=lambda k: update_when[k])
    return verison_sort[-1]


if __name__ == '__main__':
    devpi_login()
